package com.newdjk.newdoctor.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.newdjk.newdoctor.MyApplication;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.adapter.HomeFunctionAdapter;
import com.newdjk.newdoctor.adapter.HotShopAdapter;
import com.newdjk.newdoctor.adapter.ImageAdapter;
import com.newdjk.newdoctor.adapter.TeseAdviceAdapter;
import com.newdjk.newdoctor.adapter.YouxuanAdapter;
import com.newdjk.newdoctor.base.BasicFragment;
import com.newdjk.newdoctor.db.gen.LoginDataDao;
import com.newdjk.newdoctor.entity.AppLicationEntity;
import com.newdjk.newdoctor.entity.LoginData;
import com.newdjk.newdoctor.net.BaseComPleteObserver;
import com.newdjk.newdoctor.net.NetServices;
import com.newdjk.newdoctor.ui.AdsDialogActivity;
import com.newdjk.newdoctor.ui.AllFunctionActivity;
import com.newdjk.newdoctor.ui.BaseInfoActivity;
import com.newdjk.newdoctor.ui.InviteDoctorActivity;
import com.newdjk.newdoctor.ui.LoginActivity;
import com.newdjk.newdoctor.ui.MyPatientActivity;
import com.newdjk.newdoctor.ui.RenzhengActivity;
import com.newdjk.newdoctor.ui.ShareShopActivity;
import com.newdjk.newdoctor.ui.WebViewActivity;
import com.newdjk.newdoctor.utils.AppLicationUtils;
import com.newdjk.newdoctor.utils.AppUtils;
import com.newdjk.newdoctor.utils.Contants;
import com.newdjk.newdoctor.utils.Event;
import com.newdjk.newdoctor.utils.GlideUtils;
import com.newdjk.newdoctor.utils.LocationUtils;
import com.newdjk.newdoctor.utils.RxBus;
import com.newdjk.newdoctor.utils.ToastUtil;
import com.newdjk.newdoctor.view.CircleImageView;
import com.newdjk.okhttp.entity.ADentity;
import com.newdjk.okhttp.entity.AreaEntity;
import com.newdjk.okhttp.entity.BaseEntity;
import com.newdjk.okhttp.entity.GetPreEntity;
import com.newdjk.okhttp.entity.HomeTabRedEntity;
import com.newdjk.okhttp.entity.HotShopEntity;
import com.newdjk.okhttp.entity.MedicationCompanyEntity;
import com.newdjk.okhttp.entity.SpecialAdviceEntity;
import com.newdjk.okhttp.entity.YunyiYouxuanEntity;
import com.newdjk.okhttp.entity.ZhuangxiutEntity;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class HomeFragment extends BasicFragment {


    private static final String TAG = "HomeFragment";
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.im_doctor)
    CircleImageView imDoctor;
    @BindView(R.id.lv_invite)
    LinearLayout lvInvite;
    @BindView(R.id.recyleview_function)
    RecyclerView recyleviewFunction;
    @BindView(R.id.tv_hot_title)
    TextView tvHotTitle;
    @BindView(R.id.hotrecyleview)
    RecyclerView hotrecyleview;
    @BindView(R.id.lv_hot_container)
    LinearLayout lvHotContainer;
    @BindView(R.id.teseTuijianecyleview)
    RecyclerView teseTuijianecyleview;
    @BindView(R.id.tv_specil_teseService)
    TextView tvSpecilTeseService;
    @BindView(R.id.tv_specil_youxuantuijian)
    TextView tvSpecilYouxuantuijian;
    @BindView(R.id.youxuanrecyleview)
    RecyclerView youxuanrecyleview;
    @BindView(R.id.tv_more)
    TextView tvMore;
    @BindView(R.id.im_more)
    ImageView imMore;
    @BindView(R.id.tv_renzheng)
    TextView tvRenzheng;
    @BindView(R.id.tv_shop)
    TextView tvShop;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.lv_youxuantuijian)
    LinearLayout lvYouxuantuijian;
    @BindView(R.id.lv_base_info)
    LinearLayout lvBaseInfo;
    @BindView(R.id.lv_zishi_renzheng)
    LinearLayout lvZishiRenzheng;
    @BindView(R.id.lv_caiji_item)
    LinearLayout lvCaijiItem;
    @BindView(R.id.lv_youxuan_item)
    LinearLayout lvYouxuanItem;
    @BindView(R.id.lv_tesefuwu_item)
    LinearLayout lvTesefuwuItem;
    @BindView(R.id.lv_new_guide)
    LinearLayout lvNewGuide;
    @BindView(R.id.swipeLayoout)
    SwipeRefreshLayout swipeLayoout;
    @BindView(R.id.im_float_ad)
    ImageView imFloatAd;
    @BindView(R.id.im_cancel)
    ImageView imCancel;
    @BindView(R.id.lv_float_ad)
    LinearLayout lvFloatAd;


    private List<ADentity.BannerADsBean> images = new ArrayList<>();

    private Observable<Boolean> loginObservable;
    private Observable<Boolean> mineRefeshObservable;
    private Observable<Boolean> chufangObservable;
    private Observable<Boolean> tiaopeiObservable;
    private Observable<Boolean> systemObservable;
    private Observable<Boolean> refreshHomeFunction;
    private Observable<Boolean> getdoctorinfoObservable;

    private List<AppLicationEntity> listFunction = new ArrayList<>();
    private List<AppLicationEntity> listAllFunction = new ArrayList<>();
    List<HotShopEntity.ReturnDataBean.MedicationListBean> medlist = new ArrayList<>();
    List<SpecialAdviceEntity.ReturnDataBean> spcAdviceList = new ArrayList<>();
    List<YunyiYouxuanEntity.GoodsListBean> youxuanList = new ArrayList<>();


    private HomeFunctionAdapter mHomeFunctionAdapter;
    private HotShopAdapter mHotShopAdapter;
    private TeseAdviceAdapter mTeseAdviceAdapter;
    private YouxuanAdapter mYouxuanAdapter;
    private HotShopEntity hotdata;
    private ADentity addata;

    @Override
    protected int initViewResId() {
        return R.layout.fragment_home;
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initView() {

        initFunctionRecyleview();
        initFHotRecyleview();
        initTeseRecyleview();
        inityouxuanRecyleview();

        loginObservable = RxBus.get().register(Event.Login_success);
        loginObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {

                refreshHomeFunction();
                GetApplyPreListOfAuditor();
                GetApplyPreListOfChecker();
                //首页认证及装修
                GetPharmacyManagerStatus();
            }
        });
        getdoctorinfoObservable = RxBus.get().register(Event.getdoctor_info);

        getdoctorinfoObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                updateDoctorInfo();
                updateRenzhengStatus();
            }
        });

        mineRefeshObservable = RxBus.get().register(Event.mine_refresh);

        mineRefeshObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                GetApplyPreListOfAuditor();
                GetApplyPreListOfChecker();

            }
        });
        chufangObservable = RxBus.get().register(Event.chufang_refresh);

        chufangObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                //处方审核数量
                GetApplyPreListOfAuditor();
            }
        });

        tiaopeiObservable = RxBus.get().register(Event.Tiaopei_refresh);

        tiaopeiObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                //调配核对
                GetApplyPreListOfChecker();
            }
        });
        refreshHomeFunction = RxBus.get().register(Event.home_function_refresh);

        refreshHomeFunction.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                Log.d(TAG, "首页tab有更新");

                refreshHomeFunction();
                GetApplyPreListOfChecker();
                GetApplyPreListOfAuditor();

            }
        });


        systemObservable = RxBus.get().register(Event.jpush_Sysetm_list);

        systemObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                Log.d(TAG, "系统消息有更新");
                //处方审核数量
                GetApplyPreListOfAuditor();
                //调配核对
                GetApplyPreListOfChecker();
            }
        });
    }

    private void updateRenzhengStatus() {
        int doctorstus = 2;
        if (MyApplication.medicationCompanyEntity != null) {
            doctorstus = MyApplication.medicationCompanyEntity.getCheckStatus();
        } else {
            if (MyApplication.LoginEntity != null) {
                doctorstus = MyApplication.LoginEntity.getUser().getStatus();

            }
        }


        switch (doctorstus) {
            case 0:
                tvRenzheng.setText("未认证" + ",点击去认证");

                break;
            case 1:
                tvRenzheng.setText("认证中");

                break;
            case 2:
                tvRenzheng.setText("已认证");

                break;
            case 3:
                tvRenzheng.setText("认证失败" + ",点击去认证");

                break;
        }

    }

    private void updateDoctorInfo() {
        if (MyApplication.DoctorInfoEntity != null) {
            int roletype = MyApplication.DoctorInfoEntity.getRoleType();
            GlideUtils.loadDoctorImage(MyApplication.DoctorInfoEntity.getPicturePath(), imDoctor);

            //2/5/6/7/8/9/10/11/12显示账号名  2/5/6/7/8/9/10/11/12没有机构信息管理按钮  没有药店管理入口
            if (roletype == 1 || roletype == 2 || roletype == 3 || roletype == 4 || roletype == 5 || roletype == 6 || roletype == 7 || roletype == 8 || roletype == 9 || roletype == 10 || roletype == 11 || roletype == 12) {
                String name = MyApplication.DoctorInfoEntity.getDrName();
                if (!TextUtils.isEmpty(name)) {
                    if (name.length() > 14) {
                        tvName.setText(name.substring(0, 8) + "..." + name.substring(name.length() - 6, name.length()));
                    } else {
                        tvName.setText(name);
                    }
                }
                String shop = MyApplication.DoctorInfoEntity.getCompanyName();
                if (!TextUtils.isEmpty(shop)) {
                    if (shop.length() > 14) {
                        tvShop.setText(shop.substring(0, 8) + "..." + shop.substring(shop.length() - 6, shop.length()));
                    } else {
                        tvShop.setText(shop);
                    }
                }

                // tvShop.setText((TextUtils.isEmpty(t.getData().getCompanyName()) ? "" : t.getData().getCompanyName()) + "");
            } else {

                String name = MyApplication.DoctorInfoEntity.getCompanyName();
                if (!TextUtils.isEmpty(name)) {
                    if (name.length() > 14) {
                        tvName.setText(name.substring(0, 8) + "..." + name.substring(name.length() - 6, name.length()));
                    } else {
                        tvName.setText(name);
                    }
                } else {
                    String drname = MyApplication.DoctorInfoEntity.getDrName();
                    if (!TextUtils.isEmpty(drname)) {
                        if (drname.length() > 14) {
                            tvName.setText(drname.substring(0, 8) + "..." + drname.substring(drname.length() - 6, drname.length()));
                        } else {
                            tvName.setText(drname);
                        }
                    }
                }
            }


        }


    }

    private void inityouxuanRecyleview() {

        mYouxuanAdapter = new YouxuanAdapter(youxuanList);
        GridLayoutManager mManagerLayout = new GridLayoutManager(MyApplication.getContext(), 2);
        youxuanrecyleview.setLayoutManager(mManagerLayout);
        youxuanrecyleview.setAdapter(mYouxuanAdapter);
    }

    private void initFHotRecyleview() {

        mHotShopAdapter = new HotShopAdapter(medlist);
        GridLayoutManager mManagerLayout = new GridLayoutManager(MyApplication.getContext(), 3);
        hotrecyleview.setLayoutManager(mManagerLayout);
        hotrecyleview.setAdapter(mHotShopAdapter);
    }

    private void initTeseRecyleview() {

        mTeseAdviceAdapter = new TeseAdviceAdapter(spcAdviceList);
        LinearLayoutManager mManagerLayout = new LinearLayoutManager(MyApplication.getContext());
        teseTuijianecyleview.setLayoutManager(mManagerLayout);
        teseTuijianecyleview.setAdapter(mTeseAdviceAdapter);
    }

    private void refreshHomeFunction() {

        if (MyApplication.isLogin) {
            //再取出来看看
            LoginDataDao daoSession = MyApplication.getDbSession().getLoginDataDao();
            List<LoginData> querylist = daoSession.queryBuilder().where(LoginDataDao.Properties.Phone.eq(MyApplication.LoginEntity.getUser().getMobile())).list();
            Log.d(TAG, querylist.toString());
            listFunction.clear();
            //如果数据库中有数据，直接取出来显示，如果没有，先获取默认的，再存储起来

            if (querylist.size() > 0) {
                //先判断当前登录账号是否与数据库中的相同

                Log.d(TAG, "查询数据" + querylist.get(0).getList().toString());
                List<AppLicationEntity> dblist = querylist.get(0).getList();
                LoginData functionbean = querylist.get(0);

                //如果医生类型没有修改过
                if (functionbean.getType() == MyApplication.LoginEntity.getUser().getDrType()) {
                    listFunction.addAll(querylist.get(0).getList());

                } else {
                    //如果账号类型更改过，要先清空数据库
                    daoSession.queryBuilder().where(LoginDataDao.Properties.Phone.eq(MyApplication.LoginEntity.getUser().getMobile())).buildDelete().executeDeleteWithoutDetachingEntities();
                    //重新取出数据
                    listAllFunction.clear(); //所有的
                    listAllFunction.addAll(AppLicationUtils.getMedical());
                    listAllFunction.addAll(AppLicationUtils.getOperate());
                    listAllFunction.addAll(AppLicationUtils.getLearn());
                    listAllFunction.addAll(AppLicationUtils.getConfigua());

                    //然后取出来前面的  如果大于四个，就取出前面的四个
                    if (listAllFunction.size() > 4) {
                        listFunction.addAll(listAllFunction.subList(0, 4));
                    } else {//否则就全部添加进去
                        listFunction.addAll(listAllFunction);
                    }
                }

            } else {

                //取出来所有的数据
                listAllFunction.clear(); //所有的
                listAllFunction.addAll(AppLicationUtils.getMedical());
                listAllFunction.addAll(AppLicationUtils.getOperate());
                listAllFunction.addAll(AppLicationUtils.getLearn());
                listAllFunction.addAll(AppLicationUtils.getConfigua());

                //然后取出来前面的  如果大于四个，就取出前面的四个
                if (listAllFunction.size() > 4) {
                    listFunction.addAll(listAllFunction.subList(0, 4));
                } else {//否则就全部添加进去
                    listFunction.addAll(listAllFunction);
                }
            }
            AppLicationEntity appLicationEntity = new AppLicationEntity();
            appLicationEntity.setAppDesc("更多服务");
            listFunction.add(appLicationEntity);
            mHomeFunctionAdapter.notifyDataSetChanged();

        } else {

            //未登录的时候随机取出部分显示
            //取出来所有的数据
            listAllFunction.clear(); //所有的
            listAllFunction.addAll(AppLicationUtils.getMedical());
            listAllFunction.addAll(AppLicationUtils.getOperate());
            listAllFunction.addAll(AppLicationUtils.getLearn());
            listAllFunction.addAll(AppLicationUtils.getConfigua());

            //然后取出来前面的  如果大于四个，就取出前面的四个
            if (listAllFunction.size() > 4) {
                listFunction.addAll(listAllFunction.subList(0, 4));
            } else {//否则就全部添加进去
                listFunction.addAll(listAllFunction);
            }
            AppLicationEntity appLicationEntity = new AppLicationEntity();
            appLicationEntity.setAppDesc("更多服务");
            listFunction.add(appLicationEntity);
            mHomeFunctionAdapter.notifyDataSetChanged();

        }


    }

    private void initFunctionRecyleview() {

        mHomeFunctionAdapter = new HomeFunctionAdapter(listFunction);
        GridLayoutManager mManagerLayout = new GridLayoutManager(MyApplication.getContext(), 5);
        recyleviewFunction.setLayoutManager(mManagerLayout);
        recyleviewFunction.setAdapter(mHomeFunctionAdapter);
    }

    @Override
    protected void initListener() {
        mHomeFunctionAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                isNeedLoginOrRenzheng(listFunction.get(position).getAppDesc());
            }
        });

        //特色服务专区
        tvSpecilTeseService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent sevice = new Intent(getContext(), WebViewActivity.class);
                sevice.putExtra(Contants.TYPE, 27);
                getContext().startActivity(sevice);
            }
        });
        //优选推荐专区
        tvSpecilYouxuantuijian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent advice = new Intent(getContext(), WebViewActivity.class);
                advice.putExtra(Contants.TYPE, 14);
                getContext().startActivity(advice);
            }
        });

        lvHotContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (hotdata != null) {
                    if (hotdata.getReturnData() != null) {
                        if (hotdata.getReturnData().size() > 0) {
                            HotShopEntity.ReturnDataBean channedata = hotdata.getReturnData().get(0);
                            Intent caijiintent = new Intent(getContext(), WebViewActivity.class);
                            caijiintent.putExtra(Contants.TYPE, 44);
                            caijiintent.putExtra("channerid", channedata.getChannelId() + "");
                            caijiintent.putExtra("ChannelName", channedata.getChannelName() + "");
                            caijiintent.putExtra("ChannelType", channedata.getChannelType() + "");
                            getContext().startActivity(caijiintent);
                        }
                    }
                }

            }
        });

        lvInvite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent invivate = new Intent(getContext(), InviteDoctorActivity.class);
                getContext().startActivity(invivate);
            }
        });


        mYouxuanAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {


                Intent youxuan = new Intent(getContext(), WebViewActivity.class);
                youxuan.putExtra(Contants.TYPE, 43);
                youxuan.putExtra("goodID", youxuanList.get(position).getGoodsId() + "");
                getContext().startActivity(youxuan);

            }
        });

        mHotShopAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Intent caijiintent = new Intent(getContext(), WebViewActivity.class);
                caijiintent.putExtra(Contants.TYPE, 45);
                caijiintent.putExtra("medicalid", medlist.get(position).getMedicationId() + "");
                getContext().startActivity(caijiintent);
            }
        });

        mTeseAdviceAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Intent caijiintent = new Intent(getContext(), WebViewActivity.class);
                caijiintent.putExtra(Contants.TYPE, 46);
                caijiintent.putExtra("ServicePackId", spcAdviceList.get(position).getServicePackId() + "");
                getContext().startActivity(caijiintent);
            }
        });

        lvBaseInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getContext(), BaseInfoActivity.class);
                startActivity(intent);
            }
        });
        lvZishiRenzheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), RenzhengActivity.class);
                startActivity(intent);
            }
        });

        lvCaijiItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent caijiintent = new Intent(getContext(), WebViewActivity.class);
                caijiintent.putExtra(Contants.TYPE, 18);
                getContext().startActivity(caijiintent);
            }
        });

        lvYouxuanItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent advice = new Intent(getContext(), WebViewActivity.class);
                advice.putExtra(Contants.TYPE, 14);
                getContext().startActivity(advice);
            }
        });

        lvTesefuwuItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent sevice = new Intent(getContext(), WebViewActivity.class);
                sevice.putExtra(Contants.TYPE, 27);
                getContext().startActivity(sevice);
            }
        });

        swipeLayoout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {


                //首页tab功能
                refreshHomeFunction();
                //处方审核数量
                GetApplyPreListOfAuditor();
                //调配核对
                GetApplyPreListOfChecker();
                //获取我的云诊所/云药房状态
                GetPharmacyManagerStatus();

                getShop();
            }
        });

        imFloatAd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (addata != null) {
                    if (addata.getFloatAD() != null) {

                        String url = addata.getFloatAD().getLinkUrl();
                        if (!TextUtils.isEmpty(url)) {

                            if (url.startsWith("http")) {
                                Intent intent = new Intent(getContext(), WebViewActivity.class);
                                intent.putExtra("url", url);
                                intent.putExtra(Contants.TYPE, 31);
                                startActivity(intent);
                            } else {
                                Intent intent = new Intent(getContext(), WebViewActivity.class);
                                intent.putExtra("innerLink", url);
                                intent.putExtra(Contants.TYPE, 21);
                                startActivity(intent);
                            }

                        }
                    }
                }
            }
        });
    }


    //判断是否需要登录及认证
    void isNeedLoginOrRenzheng(String type) {
        Log.d(TAG, "常用" + type);
        if (type.equals("优选推荐") ||
                type.equals("药品集采")
                || type.equals("特色服务推荐") ||
                type.equals("VIP预约推荐") ||
                type.equals("肺癌早筛")) {

            gotoWebview(type);
        } else {
            if (!MyApplication.isLogin) {
                Intent intent = new Intent(getContext(), LoginActivity.class);
                intent.putExtra(Contants.toLogin, Contants.From_mainActivity);
                getContext().startActivity(intent);
                return;
            }
            // int roletype = t.getData().getRoleType();
            if (!type.equals("处方审核") && !type.equals("购药回访")) {
                if (MyApplication.medicationCompanyEntity == null) {
                    ToastUtil.setToast("请等待数据加载完成");
                    return;
                }
            }

            //   int roletype =MyApplication.DoctorInfoEntity.getRoleType();
            //  1诊所，2医生，3诊所并且是医生,4，药房  0啥都不是  诊所无申请处方
            //(认证状态。0未认证；1认证中；2已认证；3认证失败)

            if (!type.equals("处方审核")) { //用户管理未认证也能进去
                if (MyApplication.medicationCompanyEntity == null) {
                    MyApplication.medicationCompanyEntity = new MedicationCompanyEntity();
                    MyApplication.medicationCompanyEntity.setCheckStatus(MyApplication.DoctorInfoEntity.getDrStatus());
                }
                if (MyApplication.medicationCompanyEntity.getCheckStatus() != 2) {
                    AppUtils.checkAuthenStatus(MyApplication.medicationCompanyEntity.getCheckStatus(), getContext());
                    return;
                }
            }
            gotoWebview(type);
        }
    }


    @Override
    protected void initData() {

//        images.add(R.drawable.banner_1);
//        images.add(R.drawable.banner_2);
//        images.add(R.drawable.banner_3);


        //首页tab功能
        refreshHomeFunction();
        //处方审核数量
        GetApplyPreListOfAuditor();
        //调配核对
        GetApplyPreListOfChecker();


        getShop();
    }

    private void SearchAdsNew(int areid, int drid) {

        NetServices.Factory.getService().SearchAdsNew(0, areid + "", drid + ""
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<ADentity>(getActivity(), false) {
                    @Override
                    protected void onSuccees(BaseEntity<ADentity> t) throws Exception {

                        addata = t.getData();
                        //已认证且已装修就不显示该模块 0未装修；1已装修   0未认证；1认证中；2已认证；3认证失败

                        // Banner  广告
                        // PopupAD 弹窗广告
                        // FloatAD 漂浮球广告
                        List<ADentity.BannerADsBean> listbanner = t.getData().getBannerADs();
                        images.addAll(listbanner);
                        loadBannerData();
                        if (t.getData().getPopupAD() != null) {
                            if (!TextUtils.isEmpty(t.getData().getPopupAD().getLinkUrl())) {
                                Intent ads = new Intent(getContext(), AdsDialogActivity.class);
                                ads.putExtra("linkurl", t.getData().getPopupAD().getLinkUrl());
                                getContext().startActivity(ads);
                            }

                        }
                        if (t.getData().getFloatAD() != null) {
                            GlideUtils.loadgif(t.getData().getFloatAD().getLinkUrl(), imFloatAd, lvFloatAd);

                        }

                    }

                    @Override
                    protected void onFailure(Throwable e, String erroressage, boolean isNetWorkError) throws Exception {
                        super.onFailure(e, erroressage, isNetWorkError);
                    }
                });


    }

    private void GetPharmacyManagerStatus() {
        if (MyApplication.isLogin) {

            if (MyApplication.DoctorInfoEntity != null) {
                int roletype = MyApplication.DoctorInfoEntity.getRoleType();
                if (roletype == 1 || roletype == 3 || roletype == 4) {

                    NetServices.Factory.getService().GetPharmacyManagerStatus(MyApplication.LoginEntity.getUser().getDoctorId() + ""
                    ).subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new BaseComPleteObserver<ZhuangxiutEntity>(getActivity(), false) {
                                @Override
                                protected void onSuccees(BaseEntity<ZhuangxiutEntity> t) throws Exception {

                                    //已认证且已装修就不显示该模块 0未装修；1已装修   0未认证；1认证中；2已认证；3认证失败
                                    if (t.getData().getCheckStatus() == 2 && t.getData().getDecorateStatus() == 1) {
                                        lvNewGuide.setVisibility(View.GONE);
                                    } else {
                                        lvNewGuide.setVisibility(View.VISIBLE);
                                        if (t.getData().getDecorateStatus() == 0) {
                                            lvBaseInfo.setVisibility(View.VISIBLE);
                                        } else {
                                            lvBaseInfo.setVisibility(View.GONE);
                                        }

                                    }


                                }
                            });

                }

            }


        }


    }

    private void getShop() {
        LocationUtils.getinstanse().initlocation(getContext(), new LocationUtils.locationStatusListener() {
            @Override
            public void locationSuccess(String data, String location, String province, String city, String area) {
                //如果历史不为空，并且定位到了其他城市
                getProvinceLocation(city);
                LocationUtils.getinstanse().stopLocation();

                swipeLayoout.setRefreshing(false);
            }

            @Override
            public void locationFailed(String data) {
                //获取定位失败
                ToastUtil.setToast(data);
                int drid = 0;
                if (null != MyApplication.LoginEntity) {
                    drid = MyApplication.LoginEntity.getUser().getDoctorId();

                }
                QueryChannelPage(0, drid);
                QueryRecommendPackPagePage(0, drid);
                GetMallChannelList(0, drid);
                SearchAdsNew(0, drid);
                LocationUtils.getinstanse().stopLocation();
                swipeLayoout.setRefreshing(false);
            }
        });

    }

    private void getProvinceLocation(String province) {

        NetServices.Factory.getService().QueryAreaByName(province
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<AreaEntity>(getActivity(), false) {
                    @Override
                    protected void onSuccees(BaseEntity<AreaEntity> t) throws Exception {
                        int areid = t.getData().getAreaId();
                        int drid = 0;
                        if (null != MyApplication.LoginEntity) {
                            drid = MyApplication.LoginEntity.getUser().getDoctorId();

                        }
                        QueryChannelPage(areid, drid);
                        QueryRecommendPackPagePage(areid, drid);
                        GetMallChannelList(areid, drid);
                        SearchAdsNew(areid, drid);
                    }
                });
    }

    private void GetMallChannelList(int areid, int drid) {
        NetServices.Factory.getService().GetMallChannelList(drid, areid
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<List<YunyiYouxuanEntity>>(getActivity(), false) {
                    @Override
                    protected void onSuccees(BaseEntity<List<YunyiYouxuanEntity>> t) throws Exception {
                        List<YunyiYouxuanEntity> databean = t.getData();

                        if (databean != null) {
                            if (databean.size() > 0) {
                                List<YunyiYouxuanEntity.GoodsListBean> goodlist = databean.get(0).getGoodsList();
                                if (goodlist != null) {
                                    if (goodlist.size() > 6) {
                                        youxuanList.addAll(goodlist.subList(0, 6));
                                    } else {
                                        youxuanList.addAll(goodlist);
                                    }
                                }
                            }

                        }
                        if (youxuanList.size() == 0) {
                            lvYouxuantuijian.setVisibility(View.GONE);
                        } else {
                            lvYouxuantuijian.setVisibility(View.VISIBLE);

                        }
                        mYouxuanAdapter.notifyDataSetChanged();

                    }
                });
    }

    private void QueryRecommendPackPagePage(int areid, int drid) {
        NetServices.Factory.getService().QueryRecommendPackPagePage(0, -1, 1, 0, 1, 3, false, drid
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<SpecialAdviceEntity>(getActivity(), false) {
                    @Override
                    protected void onSuccees(BaseEntity<SpecialAdviceEntity> t) throws Exception {
                        SpecialAdviceEntity databean = t.getData();

                        List<SpecialAdviceEntity.ReturnDataBean> listreturn = databean.getReturnData();
                        if (listreturn != null) {
                            spcAdviceList.clear();
                            spcAdviceList.addAll(listreturn);
                            mTeseAdviceAdapter.notifyDataSetChanged();
                        }

                    }
                });
    }

    private void QueryChannelPage(int areid, int drid) {

        NetServices.Factory.getService().QueryChannelPage(1, -1, 1, 1, areid, drid
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<HotShopEntity>(getActivity(), false) {
                    @Override
                    protected void onSuccees(BaseEntity<HotShopEntity> t) throws Exception {
                        hotdata = t.getData();
                        List<HotShopEntity.ReturnDataBean> list = hotdata.getReturnData();
                        if (list != null) {
                            if (list.size() > 0) {
                                String title = list.get(0).getChannelName();
                                if (!TextUtils.isEmpty(title)) {
                                    lvHotContainer.setVisibility(View.VISIBLE);
                                    tvHotTitle.setText(title);
                                } else {
                                    lvHotContainer.setVisibility(View.GONE);
                                }
                                medlist.clear();
                                medlist.addAll(list.get(0).getMedicationList());
                                mHotShopAdapter.notifyDataSetChanged();

                            }
                        }


                    }
                });
    }


    private void GetApplyPreListOfChecker() {
        List<Integer> statuslist = new ArrayList<>();
        statuslist.add(2);
        statuslist.add(5);
        GetApplyPreStatusCount(statuslist, "调配核对");
    }

    private void GetApplyPreStatusCount(List<Integer> statuslist, String type) {

        if (MyApplication.isLogin) {
            if (null != MyApplication.LoginEntity) {
                GetPreEntity getPreEntity = new GetPreEntity();
                getPreEntity.setDoctorId(MyApplication.LoginEntity.getUser().getDoctorId());
                getPreEntity.setStatus(statuslist);
                String json = new Gson().toJson(getPreEntity);
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
                NetServices.Factory.getService().GetApplyPreStatusCount(
                        body
                ).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseComPleteObserver<List<HomeTabRedEntity>>(getActivity(), false) {
                            @Override
                            protected void onSuccees(BaseEntity<List<HomeTabRedEntity>> t) throws Exception {
                                Log.d(TAG, "新红点 " + t.toString());
                                if (t.getData() != null) {
                                    if (t.getData().size() > 0) {
                                        if (type.equals("未审方")) {
                                            int red = 0;
                                            for (int i = 0; i < t.getData().size(); i++) {
                                                red = red + t.getData().get(i).getTotalCount();
                                            }
                                            //处方审核
                                            for (int i = 0; i < listFunction.size(); i++) {
                                                if (listFunction.get(i).getAppDesc().equals("处方审核")) {
                                                    listFunction.get(i).setUnReadNum(red);
                                                }
                                            }
                                            mHomeFunctionAdapter.notifyDataSetChanged();

                                            //调配核对
                                        } else if (type.equals("调配核对")) {

                                            int red = 0;
                                            for (int i = 0; i < t.getData().size(); i++) {
                                                red = red + t.getData().get(i).getTotalCount();
                                            }
                                            for (int i = 0; i < listFunction.size(); i++) {
                                                if (listFunction.get(i).getAppDesc().equals("调配核对")) {
                                                    listFunction.get(i).setUnReadNum(red);
                                                }
                                            }
                                            mHomeFunctionAdapter.notifyDataSetChanged();

                                        }
                                    } else {
//                                        if (type.equals("未审方")) {
//                                            mVideoInterrogationAdapter.reFreshTab(0, 0, "处方审核");
//                                            //调配核对
//                                        } else if (type.equals("调配核对")) {
//                                            mVideoInterrogationAdapter.reFreshTab(0, 0, "调配核对");
//
//                                        }
                                    }

                                }

                            }

                            @Override
                            protected void onFailure(Throwable e, String erroressage, boolean isNetWorkError) throws Exception {
                                super.onFailure(e, erroressage, isNetWorkError);

                            }
                        });

            }

        }
    }

    private void GetApplyPreListOfAuditor() {
        List<Integer> statuslist = new ArrayList<>();
        statuslist.add(0);
        GetApplyPreStatusCount(statuslist, "未审方");
    }

    private void loadBannerData() {
        initbanner();
    }

    @Override
    protected void otherViewClick(View view) {

    }

    private void initbanner() {
        ImageAdapter adapter = new ImageAdapter(images);

        banner.setAdapter(adapter)//设置适配器
//              .setCurrentItem(3,false)
                .addBannerLifecycleObserver(this)//添加生命周期观察者
//              .setBannerRound(BannerUtils.dp2px(5))//圆角
//              .addPageTransformer(new RotateYTransformer())//添加切换效果
                .setIndicator(new CircleIndicator(getContext()))//设置指示器
                .setOnBannerListener((data, position) -> {
                    LogUtils.d("position：" + position);
                    if (!TextUtils.isEmpty(images.get(position).getLinkUrl())) {
                        String url = images.get(position).getLinkUrl();
                        if (!TextUtils.isEmpty(url)) {

                            if (url.startsWith("http")) {
                                Intent intent = new Intent(getContext(), WebViewActivity.class);
                                intent.putExtra("url", images.get(position).getLinkUrl());
                                intent.putExtra(Contants.TYPE, 31);
                                startActivity(intent);
                            } else {
                                Intent intent = new Intent(getContext(), WebViewActivity.class);
                                intent.putExtra("innerLink", images.get(position).getLinkUrl());
                                intent.putExtra(Contants.TYPE, 21);
                                startActivity(intent);
                            }
                        }

                    }

                });//设置点击事件,传this也行

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(Event.Login_success, loginObservable);
        RxBus.get().unregister(Event.chufang_refresh, chufangObservable);
        RxBus.get().unregister(Event.Tiaopei_refresh, tiaopeiObservable);
        RxBus.get().unregister(Event.mine_refresh, mineRefeshObservable);
        RxBus.get().unregister(Event.home_function_refresh, refreshHomeFunction);
        RxBus.get().unregister(Event.getdoctor_info, getdoctorinfoObservable);
    }


    private void gotoWebview(String type) {

        switch (type) {
            case "药品集采":
                Intent caijiintent = new Intent(getContext(), WebViewActivity.class);
                caijiintent.putExtra(Contants.TYPE, 18);
                getContext().startActivity(caijiintent);
                break;
            case "用户管理":
                Intent paeientintent = new Intent(getContext(), MyPatientActivity.class);
                getContext().startActivity(paeientintent);
                break;
            case "快速售药":
                Intent quicksell = new Intent(getContext(), WebViewActivity.class);
                quicksell.putExtra(Contants.TYPE, 11);
                getContext().startActivity(quicksell);
                break;
            case "申请坐诊":///apply/applySitDr
                Intent applyzuozhen = new Intent(getContext(), WebViewActivity.class);
                applyzuozhen.putExtra(Contants.TYPE, 2);
                getContext().startActivity(applyzuozhen);
                break;
            case "医废申请":
                Intent yifei = new Intent(getContext(), WebViewActivity.class);
                yifei.putExtra(Contants.TYPE, 10);
                getContext().startActivity(yifei);
                break;
            case "邀请医护":

                Intent invivate = new Intent(getContext(), InviteDoctorActivity.class);
                getContext().startActivity(invivate);
                break;
            case "发布公告":
                Intent publish = new Intent(getContext(), WebViewActivity.class);
                publish.putExtra(Contants.TYPE, 8);
                getContext().startActivity(publish);
                break;
            case "申请处方":
                Intent shenqing = new Intent(getContext(), WebViewActivity.class);
                shenqing.putExtra(Contants.TYPE, 15);
                getContext().startActivity(shenqing);

                break;

            case "优选推荐":
                Intent advice = new Intent(getContext(), WebViewActivity.class);
                advice.putExtra(Contants.TYPE, 14);
                getContext().startActivity(advice);
                break;
            case "扫码入库":
                Intent scan = new Intent(getContext(), WebViewActivity.class);
                scan.putExtra(Contants.TYPE, 12);
                getContext().startActivity(scan);
                break;
            case "分享店铺":
                Intent share = new Intent(getContext(), ShareShopActivity.class);
                getContext().startActivity(share);
                break;
            case "基础设置":
                Intent basic = new Intent(getContext(), WebViewActivity.class);
                basic.putExtra(Contants.TYPE, 9);
                getContext().startActivity(basic);
                break;
            case "特色服务推荐":

                Intent sevice = new Intent(getContext(), WebViewActivity.class);
                sevice.putExtra(Contants.TYPE, 27);
                getContext().startActivity(sevice);
                break;

            case "VIP预约推荐":
                Intent vip = new Intent(getContext(), WebViewActivity.class);
                vip.putExtra(Contants.TYPE, 28);
                getContext().startActivity(vip);
                break;

            case "肺癌早筛":
                Intent threemorning = new Intent(getContext(), WebViewActivity.class);
                threemorning.putExtra(Contants.TYPE, 29);
                getContext().startActivity(threemorning);
                break;

            case "处方审核":
//                mSelectedPictureDialog = new SelectedIDcardDialog(getActivity(), this, "first");
//                mSelectedPictureDialog.show();

                Intent chufang = new Intent(getContext(), WebViewActivity.class);
                chufang.putExtra(Contants.TYPE, 34);
                getContext().startActivity(chufang);
                break;

            case "调配核对":
//                ToastUtil.setToast("调配核对");
                Intent tiaopei = new Intent(getContext(), WebViewActivity.class);
                tiaopei.putExtra(Contants.TYPE, 35);
                getContext().startActivity(tiaopei);
                break;


            case "购药回访":
                Intent huifang = new Intent(getContext(), WebViewActivity.class);
                huifang.putExtra(Contants.TYPE, 41);
                getContext().startActivity(huifang);
                break;

            case "更多服务":
                Intent intent = new Intent(getContext(), AllFunctionActivity.class);
                startActivity(intent);
                break;
        }
    }


}
